package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.domain.User;
import com.example.demo.entity.ChatMessage;
import com.example.demo.entity.Messages;
import com.example.demo.service.MessagesService;
import com.example.demo.mapper.MessagesMapper;
import com.example.demo.service.UserService;
import com.example.demo.utils.TokenUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
* @author 86187
* @description 针对表【messages(聊天消息表)】的数据库操作Service实现
* @createDate 2025-06-19 10:03:28
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class MessagesServiceImpl extends ServiceImpl<MessagesMapper, Messages>
    implements MessagesService{

    private final UserService userService;
    private final SimpMessagingTemplate messagingTemplate;

    @Override
    public List<Messages> getMessage(String token, String receiverId, String isGroup) {
        Map<String, String> tokenMap = TokenUtil.parseToken(token);
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUserName, tokenMap.get("userName")));
        
        log.info("查询消息 - 当前用户: {}, ID: {}, 接收者ID: {}, 是否群聊: {}", 
                user.getUserName(), user.getId(), receiverId, isGroup);
        
        // 转换isGroup参数
        boolean isGroupBool = "true".equalsIgnoreCase(isGroup);
        
        // 构建查询条件
        LambdaQueryWrapper<Messages> msgWrapper = new LambdaQueryWrapper<>();
        msgWrapper.nested(wrapper -> wrapper
                .nested(w -> w.eq(Messages::getSenderId, Long.valueOf(user.getId()))
                             .eq(Messages::getReceiverId, Long.valueOf(receiverId)))
                .or()
                .nested(w -> w.eq(Messages::getSenderId, Long.valueOf(receiverId))
                             .eq(Messages::getReceiverId, Long.valueOf(user.getId())))
        )
        .eq(Messages::getIsGroup, isGroupBool)
        .eq(Messages::getDeleteFlag, 0)
        .orderByAsc(Messages::getCreateTime);
        
        // 执行查询
        List<Messages> messagesList = list(msgWrapper);
        
        log.info("查询结果 - 消息数量: {}", messagesList.size());
        if (!messagesList.isEmpty()) {
            log.info("第一条消息: senderId={}, receiverId={}, content={}", 
                    messagesList.get(0).getSenderId(), 
                    messagesList.get(0).getReceiverId(),
                    messagesList.get(0).getContent());
        }
        
        return messagesList;
    }

    @Override
    public String sendMessage(String token, Messages message) {
        Map<String, String> tokenMap = TokenUtil.parseToken(token);
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUserName, tokenMap.get("userName")));
        
        log.info("发送消息 - 当前用户: {}, ID: {}, 接收者ID: {}, 内容: {}", 
                user.getUserName(), user.getId(), message.getReceiverId(), message.getContent());
        
        // 设置消息ID
        message.setMessageId(UUID.randomUUID().toString().replace("-", ""));
        // 设置发送者ID
        message.setSenderId(Long.valueOf(user.getId()));
        // 设置创建时间和更新时间
        Date now = new Date();
        message.setCreateTime(now);
        message.setUpdateTime(now);
        // 设置消息状态为已发送(1)
        message.setStatus(1);
        // 设置删除标记为未删除(0)
        message.setDeleteFlag(0);
        // 如果转发数为空，设置为0
        if (message.getForwardCount() == null) {
            message.setForwardCount(0);
        }
        
        // 如果isGroup为空，设置为false
        if (message.getIsGroup() == null) {
            message.setIsGroup(false);
        }
        
        // 保存消息
        boolean saved = save(message);
        
        log.info("消息保存结果: {}", saved ? "成功" : "失败");
        
        // 如果保存成功，通过WebSocket发送消息
        if (saved) {
            try {
                // 创建WebSocket消息
                ChatMessage chatMessage = new ChatMessage();
                chatMessage.setType(ChatMessage.MessageType.CHAT);
                chatMessage.setSenderId(message.getSenderId());
                chatMessage.setReceiverId(message.getReceiverId());
                chatMessage.setContent(message.getContent());
                chatMessage.setSenderName(user.getUserName());
                chatMessage.setIsGroup(message.getIsGroup());
                chatMessage.setMessageId(message.getMessageId());
                chatMessage.setTimestamp(now.getTime());
                
                // 发送WebSocket消息
                if (message.getIsGroup()) {
                    // 群聊消息
                    messagingTemplate.convertAndSend("/topic/group." + message.getReceiverId(), chatMessage);
                } else {
                    // 私聊消息
                    messagingTemplate.convertAndSendToUser(
                        message.getReceiverId().toString(),
                        "/queue/messages",
                        chatMessage
                    );
                    
                    // 同时发送给发送者（用于多端同步）
                    messagingTemplate.convertAndSendToUser(
                        message.getSenderId().toString(),
                        "/queue/messages",
                        chatMessage
                    );
                }
                
                log.info("WebSocket消息发送成功");
            } catch (Exception e) {
                log.error("WebSocket消息发送失败", e);
            }
            
            return "消息发送成功";
        } else {
            return "消息发送失败";
        }
    }
    
    @Override
    public Map<String, Integer> getUnreadMessageCount(String token) {
        Map<String, String> tokenMap = TokenUtil.parseToken(token);
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUserName, tokenMap.get("userName")));
        
        // 查询所有发送给当前用户且未读的消息
        LambdaQueryWrapper<Messages> unreadWrapper = new LambdaQueryWrapper<>();
        unreadWrapper.eq(Messages::getReceiverId, Long.valueOf(user.getId()))
                    .eq(Messages::getStatus, 1) // 状态为已发送
                    .isNull(Messages::getReadTime) // 未读时间为空
                    .eq(Messages::getDeleteFlag, 0); // 未删除
        
        List<Messages> unreadMessages = list(unreadWrapper);
        
        // 按发送者ID分组，统计每个发送者的未读消息数量
        Map<String, Integer> unreadCountMap = new HashMap<>();
        
        if (unreadMessages != null && !unreadMessages.isEmpty()) {
            Map<Long, Long> countBySender = unreadMessages.stream()
                .collect(Collectors.groupingBy(Messages::getSenderId, Collectors.counting()));
            
            // 转换为String, Integer格式
            countBySender.forEach((senderId, count) -> {
                unreadCountMap.put(String.valueOf(senderId), count.intValue());
            });
        }
        
        return unreadCountMap;
    }
    
    @Override
    @Transactional
    public String markMessagesAsRead(String token, String senderId) {
        Map<String, String> tokenMap = TokenUtil.parseToken(token);
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUserName, tokenMap.get("userName")));
        
        // 查询指定发送者发送给当前用户的所有未读消息
        LambdaUpdateWrapper<Messages> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Messages::getReceiverId, Long.valueOf(user.getId()))
                    .eq(Messages::getSenderId, Long.valueOf(senderId))
                    .eq(Messages::getStatus, 1) // 状态为已发送
                    .isNull(Messages::getReadTime) // 未读时间为空
                    .eq(Messages::getDeleteFlag, 0); // 未删除
        
        // 更新为已读状态
        Messages updateEntity = new Messages();
        updateEntity.setReadTime(new Date()); // 设置已读时间
        
        boolean updated = update(updateEntity, updateWrapper);
        
        // 如果有消息被标记为已读，发送已读回执
        if (updated) {
            try {
                // 创建已读回执消息
                ChatMessage readReceipt = new ChatMessage();
                readReceipt.setType(ChatMessage.MessageType.READ);
                readReceipt.setSenderId(Long.valueOf(user.getId()));
                readReceipt.setReceiverId(Long.valueOf(senderId));
                readReceipt.setSenderName(user.getUserName());
                readReceipt.setTimestamp(System.currentTimeMillis());
                
                // 发送已读回执
                messagingTemplate.convertAndSendToUser(
                    senderId,
                    "/queue/read-receipts",
                    readReceipt
                );
                
                log.info("已读回执发送成功");
            } catch (Exception e) {
                log.error("已读回执发送失败", e);
            }
            
            return "标记已读成功";
        } else {
            return "没有未读消息需要标记";
        }
    }
}




